package cn.batch.daemon.loadBatch;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.batch.daemon.Configuration;
import cn.batch.daemon.hibernate.bean.PbocSummary;
import cn.batch.daemon.service.IProcReportService;
import cn.batch.daemon.util.BuildPbocSummary;
import cn.batch.daemon.util.ConstantParameter;
import cn.batch.daemon.util.DateUtil;

public class LoadProcReportFromLocal {

	private static final Log logger = LogFactory
	.getLog(LoadProcReportFromLocal.class);
	
	private ApplicationContext ctx;
	private IProcReportService procReportService;
	private Configuration config;
	
	private String errorFileImportUrl;
	private Date batchDate;
	private String bDateString = "";
	private int runDays = 1;
	
	private int totalNumber;
	private int errorNumber;

	/**
	 * @param config
	 */
	public LoadProcReportFromLocal(Configuration config) {
		super();
		this.config = config;
	}

	public void run() {
		initialize();
		handelDir();
	}

	private void initialize() {
		if (ctx == null) {
			ctx = new ClassPathXmlApplicationContext(
					new String[] { "applicationContext*.xml" });
		}

		procReportService = (IProcReportService) ctx
				.getBean("procReportService");
		errorFileImportUrl = config.getSetting(ConstantParameter.PROC_FILE_ERROR_IMPORT_URL, "");
	}
	
	private void handelDir() {
		long startTime = System.currentTimeMillis();
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(batchDate);
		
		for (int i = 0; i < runDays; i++) {
			bDateString = DateUtil.currDayData(batchDate, "yyyyMMdd");
			
			File filePath = new File(errorFileImportUrl + bDateString);
			try {
				loadProcFile(filePath);
				logger.info("批次：" + bDateString + "，文件数：" + totalNumber + "，失败: "+ errorNumber);
			} catch (IOException e) {
				logger.warn("处理出错，批次："+bDateString, e);
			}
			
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			batchDate = calendar.getTime();
		}
		
		long along = System.currentTimeMillis() - startTime;
		logger.info("结束处理人行征信文件，共耗时（毫秒）：" + along);
	}

	/**
	 * 处理人行征信文件 。
	 * @throws IOException
	 */
	private void loadProcFile(File filepath) throws IOException {
			logger.info("开始处理批次：" + filepath.getName());
			totalNumber = 0;
			errorNumber = 0;
			// 将文件解压缩
			//UnZipFile.unZipFiles(file, outDirPath);

			if (!filepath.exists()) {
				throw new FileNotFoundException("文件不存在。");
			}
			File[] xmlFiles = filepath.listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					return pathname.getName().endsWith(".xml");
				}
			});
			totalNumber = xmlFiles.length;
			for (int i = 0; i < totalNumber; i++) {
				try {
					//增加参数fileName(解析文件名称)解决空征信报告问题 HLRain 20130829
					savePbocSummary(xmlFiles[i],xmlFiles[i].getName());
				} catch (Exception e) {
					logger.error("解析人行征信XML文件时出错。文件名: " + xmlFiles[i].getName(),
							e);
					errorNumber++;
				}
			}
	}


	private void savePbocSummary(File xmlFile,String fileName) throws Exception {

		SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
		PbocSummary pbocSummary = BuildPbocSummary.bulidPbocSummary(xmlFile, bDateString,fileName);

		PbocSummary qp = new PbocSummary();
		qp.setName(pbocSummary.getName());
		qp.setCertno(pbocSummary.getCertno());
		qp.setCerttype(pbocSummary.getCerttype());
		List<PbocSummary> list = procReportService.queryPbocSummary(qp);
		boolean isInsert = false;
		if (list.size() > 0) {
			for (PbocSummary pbocSummary2 : list) {
				if (sf.parse(pbocSummary2.getQuerytime()).before(sf.parse(pbocSummary.getQuerytime()))) {
					procReportService.deletePbocSummary(pbocSummary2);
					isInsert = true;
					logger.info(new StringBuilder("Delete Repeating Data: ")
					.append(pbocSummary2.getQuerytime()).append(", ")
					.append(pbocSummary2.getName()).append(", ")
					.append(pbocSummary2.getCertno()).append(", ")
					.append(pbocSummary2.getCerttype())
					.toString());
				}
			}
		} else {
			procReportService.savePbocSummary(pbocSummary);
		}
		if (isInsert) {
			procReportService.savePbocSummary(pbocSummary);
		}
	}
	
	/**
	 * @param runDays the runDays to set
	 */
	public void setRunDays(int runDays) {
		this.runDays = runDays;
	}

	public void setBatchDate(Date batchDate) {
		this.batchDate = batchDate;
	}
}
